/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.connector.server.prototype;

import com.je.connector.base.codec.PacketDecoder;
import com.je.connector.base.connection.Connection;
import com.je.connector.base.connection.channel.NettyChannelSocketChannel;
import com.je.connector.base.connection.impl.NettyConnection;
import com.je.connector.base.connection.registry.ConnectionRegistry;
import com.je.connector.base.message.PacketReceiver;
import com.je.connector.base.protocol.Packet;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * WebSocket通道入站处理器
 *
 * @ProjectName: instant-message
 * @Package: com.connector.base.handler
 * @ClassName: WebSocketChannelHandler
 * @Description: WebSocket通道处理器
 * @Author: LIULJ
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2018</p>
 */
@Slf4j
@ChannelHandler.Sharable
public class WebSocketChannelHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    private final ConnectionRegistry connectionRegistry;
    private final PacketReceiver receiver;

    public WebSocketChannelHandler(ConnectionRegistry connectionRegistry, PacketReceiver receiver) {
        this.connectionRegistry = connectionRegistry;
        this.receiver = receiver;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) {
        if (frame instanceof TextWebSocketFrame) {
            String text = ((TextWebSocketFrame) frame).text();
            Connection connection = connectionRegistry.get(new NettyChannelSocketChannel(ctx.channel()));
            Packet packet = PacketDecoder.decodeFrame(text);
            if (null == packet) {
                return;
            }
            log.debug("channelRead conn={}, packet={}", ctx.channel(), connection.getSessionContext(), packet);
            //进行自定义过滤器处理
            receiver.onReceive(packet, connection);
        } else {
            throw new UnsupportedOperationException(String.format("unsupported frame type: " + frame.getClass().getName()));
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        Connection connection = connectionRegistry.get(new NettyChannelSocketChannel(ctx.channel()));
        log.error("client caught ex, conn={}", connection, cause);
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("websocketclient connected conn={}", ctx.channel());
        Connection connection = new NettyConnection();
        connection.init(new NettyChannelSocketChannel(ctx.channel()));
        connectionRegistry.add(connection);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Connection connection = connectionRegistry.removeAndClose(new NettyChannelSocketChannel(ctx.channel()));
        if (null != connection && null != connection.getSessionContext()) {
            String userId = connection.getSessionContext().getUserId();
            log.info("socket连接断开:{}", userId);
        } else {
            log.info("socket连接断开");
        }
    }
}
